package com.sdk.auth.utils;

import cn.hutool.json.JSONUtil;
import com.sdk.auth.entity.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * HTTP 请求工具
 * 采集日志需要配置
 */
public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger("authtool");

    private static final String APP_NAME = "authtool";

    /**
     * Saas统一请求内部服务工具封装
     * @param url
     * @param headers
     * @param body
     * @param time
     * @param
     * @return
     */
    public static BaseResult postJson(String url, Map<String, String> headers, String body, Integer time){
        long startTime = System.currentTimeMillis();
        BaseResult resp;
        try{
            Integer timeout = null == time ? 5 : time;
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest.Builder builder = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json;charset=utf-8")
                    .POST(HttpRequest.BodyPublishers.ofString(null != body ? body : ""))
                    .timeout(Duration.ofSeconds(timeout));
            // 封装请求头
            if (headers != null && !headers.keySet().isEmpty()) {
                for (String key : headers.keySet()) {
                    builder.header(key, headers.get(key));
                }
            }
            HttpRequest request = builder.build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            long endTime = System.currentTimeMillis();
            long costTime = endTime - startTime;
            int responseCode = response.statusCode();
            resp = responseCode == HttpURLConnection.HTTP_OK ? JSONUtil.toBean(response.body(), BaseResult.class) : null;
            logAccess(url, "post",  responseCode, costTime, headers, body, resp, null);
        }catch (Exception e){
            resp = null;
            long endTime = System.currentTimeMillis();
            long costTime = endTime - startTime;
            logAccess(url, "post",  -1, costTime, headers, body, resp, e.getMessage());
        }
        return resp;
    }

    public static void logAccess(String url, String method,  int httpCode, long costTime, Map<String, String> header, String body, BaseResult resp, String error) {
        Map<String, Object> map = new HashMap<>();
        map.put("time", System.currentTimeMillis());
        map.put("appName", APP_NAME);
        map.put("url", url);
        map.put("method", method);
        map.put("httpCode", httpCode);
        map.put("costTime", costTime);
        map.put("header", header);
        map.put("body", body);
        if(null == resp){
            map.put("code", -1);
            map.put("msg", "操作失败!");
        }else{
            map.put("code", resp.getCode());
            map.put("msg", resp.getMsg());
        }
        if(error != null && error!= "" && error.length() > 0){
            map.put("error", error);
        }
        logger.info(JSONUtil.toJsonStr(map));
    }
}
